<?php
C_base::yn_file('base'.DS.'class.table.php');
C_base::yn_file('base'.DS.'class.config.php');
class db{
	
	static $_dbnames;
	
	var $_tables = array();
	var $_conn = array();
	var $_db_config;
	var $_tablenum = 0;
	var $_dbname;
	
	function __construct($dbname,$db_config,$coding = 'utf8'){
		$this->_dbname = $dbname;
		$this->_db_config = array('dbname'=>$dbname,'db_config'=>$db_config,'coding'=>$coding);
		$this->_conn['w'] = $this->_dbconn($dbname,$db_config['w'],$coding);
		$this->_conn['r'] = $this->_dbconn($dbname,$db_config['r'],$coding);
	}
	
	function _dbconn($dbname,$db_config,$coding){
		$conn = mysql_connect($db_config['host'].':'.$db_config['port'],$db_config['user'],$db_config['pwd'],true) or die("mysql error:{$dbname}!");
		mysql_query("SET character_set_client='{$coding}'",$conn);
		mysql_query("SET character_set_connection='{$coding}'",$conn);
		mysql_query("SET character_set_results='{$coding}'",$conn);
		mysql_select_db($dbname,$conn) or die (mysql_error());
		return $conn;
	}
	
	/**
	 * 
	 * @param 库名 $dbname
	 * @param 字符集 $coding
	 * @return Db
	 */
	static function Single($dbname,$coding = 'utf8'){
		if(@!self::$_dbnames["$dbname"]){
			self::$_dbnames["$dbname"] = new Db($dbname,Config::db($dbname),$coding);
		}
		return self::$_dbnames["$dbname"];
	}
	
	function __get($vn){
		if(@!$this->_tables["$vn"]){
			$this->_tablenum++;
			$this->_tables["$vn"] = new Table($this->_conn,$vn);
		}
		return $this->_tables["$vn"];
	}

}
/*********************************************************************文件已结束*****************************************************************/